<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.query"
        placeholder="请输入用户名或真实姓名"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
        添加
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="ID" prop="id" align="center" width="80" />
      <el-table-column label="用户名" prop="userName" align="center" />
      <el-table-column label="真实姓名" prop="realName" align="center" />
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" align="center" width="180" />
      <el-table-column label="操作" align="center" width="230">
        <template #default="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">
            编辑
          </el-button>
          <el-button
            type="danger"
            size="mini"
            @click="handleDelete(scope.row)"
            :disabled="scope.row.userName === 'admin'"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <!-- 编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="temp.userName" :disabled="dialogStatus==='update'" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" type="password" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="temp.realName" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="temp.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import  axios from '@/util/axios'
import Pagination from '@/components/Pagination'

const list = ref([])
const total = ref(0)
const listLoading = ref(true)
const dialogFormVisible = ref(false)
const dialogStatus = ref('')
const dialogTitle = ref('')

const listQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  query: ''
})

const temp = reactive({
  id: undefined,
  userName: '',
  password: '',
  realName: '',
  status: 1
})

const rules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }]
}

// 获取列表数据
const getList = async() => {
  listLoading.value = true
  try {
    const url = 'admin/customerService/list';
    // 手动拼接参数到URL上
    let queryString = '';
    for (const key in listQuery) {
      if (listQuery.hasOwnProperty(key)) {
        if (queryString.length > 0) {
          queryString += '&';
        }
        queryString += `${key}=${listQuery[key]}`;
      }
    }
    const fullUrl = `${url}?${queryString}`;

    
    const { data } = await axios.get(fullUrl)
    list.value = data.records
    total.value = data.total
  } catch (error) {
    console.error(error)
  }
  listLoading.value = false
}

// 搜索
const handleFilter = () => {
  listQuery.pageNum = 1
  getList()
}

// 重置表单
const resetTemp = () => {
  Object.assign(temp, {
    id: undefined,
    userName: '',
    password: '',
    realName: '',
    status: 1
  })
}

// 打开创建弹窗
const handleCreate = () => {
  resetTemp()
  dialogStatus.value = 'create'
  dialogTitle.value = '创建客服'
  dialogFormVisible.value = true
}

// 创建数据
const createData = async() => {
  try {
    await axios.post('admin/customerService/add', temp)
    dialogFormVisible.value = false
    ElMessage.success('创建成功')
    getList()
  } catch (error) {
    console.error(error)
  }
}

// 打开更新弹窗
const handleUpdate = (row) => {
  Object.assign(temp, row)
  dialogStatus.value = 'update'
  dialogTitle.value = '编辑客服'
  dialogFormVisible.value = true
}

// 更新数据
const updateData = async() => {
  try {
    await axios.post('admin/customerService/update', temp)
    dialogFormVisible.value = false
    ElMessage.success('更新成功')
    getList()
  } catch (error) {
    console.error(error)
  }
}

// 删除数据
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该客服吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    try {
      await axios.get("admin/customerService/delete/"+row.id);
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error(error)
    }
  })
}

onMounted(() => {
  getList()
})
</script>
